package com.share.shareplatform.shareuser.service.impl;


import com.share.shareplatform.pojo.Authority;
import com.share.shareplatform.pojo.Role;
import com.share.shareplatform.pojo.SecurityUser;
import com.share.shareplatform.pojo.User;
import com.share.shareplatform.shareuser.dao.UserDao;
import com.share.shareplatform.shareuser.util.AuthorityOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailsService")
public class SecurityUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userDao.findForeignOneByUsername(s);

        if(user == null) {//数据库没有用户名，认证失败
            throw  new UsernameNotFoundException("用户名不存在！");
        }

        Role role=user.getRole();
        StringBuilder builder=new StringBuilder();

        if(role==null){
            throw new UsernameNotFoundException("未知异常！");
        }

        builder.append(role.getName());
        builder.append(',');
        List<Authority> authorityList = role.getAuthorityList();
        authorityList.forEach(authority -> {
            builder.append(AuthorityOperation.getOperation(authority.getModule()+authority.getOperation())+",");
        });
        //删除最后一个','
        if(builder.charAt(builder.length()-1)==','){
            builder.deleteCharAt(builder.length()-1);
        }
        System.out.println(builder.toString());
        List<GrantedAuthority> auths =
                AuthorityUtils.commaSeparatedStringToAuthorityList(builder.toString());

        //从查询数据库返回users对象，得到用户名和密码，返回
        return new SecurityUser(user.getId(),user.getUsername(),
                new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }

}
